import { Module, NestModule, MiddlewareConsumer, RequestMethod, Global } from '@nestjs/common';
import { UserService } from './user.service';
import { UserController } from './user.controller';
// import { XiaomanService } from 'src/xiaoman/xiaoman.service';
import { LoggerMiddleware } from '../../logger/logger.middleware';
import { User } from './entities/user.entity';
import { Tags } from './entities/tags.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserRepository } from './user.repository';
import { TYPEORM_DATABASE } from '@/database/database.constants';
import { UserSchema } from './schema/user.schema';
import { MongooseModule } from '@/database/mongoose/mongoose.module';
import { RoleModule } from '../role/role.module';

@Global() // 全局模块
@Module({
  imports: [
    TypeOrmModule.forFeature([User, Tags], TYPEORM_DATABASE), // 关联实体
    MongooseModule.forFeature([{ name: 'User', schema: UserSchema }]),
    RoleModule
  ],
  controllers: [UserController],
  // providers: [UserService], // 语法糖格式
  providers: [
    {
      provide: 'User',    // 依赖注入，完整形式，provide: 'User'，User为key，UserService为value，需要在controller的实例进行@Inject注入
      useClass: UserService,
    },
    {
      provide: "JD",      // 自定义注入值
      useValue: ['TB', 'PDD', 'JD']
    },
    /* {
      provide: "Test",   // 自定义注入值
      inject: [UserService],   // 注入User
      useFactory: (UserService) => {   // 工厂方法, 如果服务 之间有相互的依赖 或者逻辑处理 可以使用 useFactory
        return new XiaomanService(UserService)
      }
    }, */
    {
      provide: 'sync',
      useFactory: async () => {
        return await new Promise((resolve) => {
          setTimeout(() => {
            resolve('sync')
          }, 3000)
        })
      }
    },
    UserRepository
  ],
  exports: [UserRepository]
})
export class UserModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {   // 局部使用
    consumer
      .apply(LoggerMiddleware)
      // .forRoutes(UserController); // 表示拦截UserController的所有路由
      .forRoutes({ path: 'user', method: RequestMethod.GET }); // 表示拦截UserController的GET请求
  }
}
